import { create } from 'zustand';

interface Enemy {
  id: string;
  name: string;
  level: number;
  health: number;
  maxHealth: number;
  attack: number;
  defense: number;
  experience: number;
  gold: number;
  description: string;
}

interface BattleState {
  enemy: Enemy;
  battleState: 'player_turn' | 'enemy_turn' | 'ended';
}

interface BattleResult {
  enemyDefeated: boolean;
  playerDefeated: boolean;
}

interface BattleStore {
  currentBattle: BattleState | null;
  battleState: 'player_turn' | 'enemy_turn' | 'ended';
  
  startBattle: (enemy: Enemy) => void;
  endBattle: () => void;
  resetBattle: () => void;
  playerAttack: (skillId: string, damage: number) => BattleResult;
  enemyAttack: (damage: number) => BattleResult;
}

export const useBattleStore = create<BattleStore>((set, get) => ({
  currentBattle: null,
  battleState: 'ended',

  startBattle: (enemy: Enemy) => {
    const battleEnemy = { ...enemy, health: enemy.maxHealth };
    
    set({ 
      currentBattle: {
        enemy: battleEnemy,
        battleState: 'player_turn'
      },
      battleState: 'player_turn'
    });
  },

  endBattle: () => {
    set({ 
      currentBattle: null,
      battleState: 'ended'
    });
  },

  resetBattle: () => {
    set({ 
      currentBattle: null,
      battleState: 'ended'
    });
  },

  playerAttack: (skillId: string, damage: number) => {
    const state = get();
    if (!state.currentBattle || state.battleState !== 'player_turn') {
      return { enemyDefeated: false, playerDefeated: false };
    }

    const newEnemyHealth = Math.max(0, state.currentBattle.enemy.health - damage);
    const enemyDefeated = newEnemyHealth <= 0;

    set({
      currentBattle: {
        ...state.currentBattle,
        enemy: {
          ...state.currentBattle.enemy,
          health: newEnemyHealth
        }
      },
      battleState: enemyDefeated ? 'ended' : 'enemy_turn'
    });

    return { enemyDefeated, playerDefeated: false };
  },

  enemyAttack: (damage: number) => {
    const state = get();
    if (!state.currentBattle || state.battleState !== 'enemy_turn') {
      return { enemyDefeated: false, playerDefeated: false };
    }

    // 这里我们不直接修改玩家血量，而是返回结果让调用者处理
    const playerDefeated = damage >= 100; // 简化的判断逻辑

    set({
      battleState: playerDefeated ? 'ended' : 'player_turn'
    });

    return { enemyDefeated: false, playerDefeated };
  }
}));